<template>
  <div style="width: 100%">
    <div class="flexDiv">
      <div class="card-title">{{ name }}</div>
      <div>
        <el-button
          type="text"
          icon="el-icon-close"
          @click="goback"
          style="color: black"
        ></el-button>
      </div>
    </div>

    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="时间选择">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          size="small"
          style="width: 350px"
          range-separator="-"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          align="right"
          @change="search"
          @blur="search"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="search"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="reset"
          >重置</el-button
        >
      </el-form-item>
      <el-form-item>
        <div class="right-title">
          仅展示当前一周之内的数据图像，超出时间范围将以列表形式呈现
        </div>
      </el-form-item>
    </el-form>
    <!-- 七天之内的数据 -->
    <div class="card-content" style="display: flex" v-show="!showAll">
      <div class="card-left">
        <div class="title">
          <div class="title-name">时间排序:</div>
        </div>
        <el-table
          :data="detailData"
          style="width: 100%"
          class="tableBox"
          :max-height="conheight"
          id="tableBox"
          @row-click="handleClickChange"
          :row-class-name="tableRowClassName"
        >
          <el-table-column label="序号" prop="index" width="55" align="center">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="collectTime"
            label="具体时间"
            width="200"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="paramNumber" label="当前值" align="center">
            <template slot-scope="scope">
              <span
                :class="
                  scope.row.paramObjectList[0].paramNumber <
                  scope.row.paramObjectList[0].min
                    ? 'max'
                    : scope.row.paramObjectList[0].paramNumber >
                      scope.row.paramObjectList[0].max
                    ? 'max'
                    : ''
                "
                >{{ formatParamValue(scope.row.paramObjectList[0]) }}</span
              ><span style="margin: 0px 6px">{{
                scope.row.paramObjectList[0].unit
              }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="card-right">
        <div class="title-name">趋势图:</div>
        <div
          id="chart"
          style="width: 680px; height: 460px; margin: -10px 20px 20px 40px"
          class=""
          ref="chart"
          v-show="!showAll"
        ></div>
      </div>
    </div>
    <!-- 超过七天的图表形式 -->
    <div class="card-content1" v-show="showAll">
      <div class="title">
        <div class="title-name">报表详情:</div>
      </div>
      <div style="display: flex">
        <div class="card-table">
          <el-table
            :data="detailData"
            style="width: 98%"
            class="tableBox"
            stripe
            :max-height="conheight"
          >
            <el-table-column
              label="序号"
              prop="index"
              width="55"
              align="center"
            >
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="paramterName" label="参数名" align="center">
              {{ name }}
            </el-table-column>
            <el-table-column
              prop="collectTime"
              label="具体时间"
              align="center"
              width="200"
            >
            </el-table-column>
            <el-table-column
              prop="paramNumber"
              label="当前值"
              align="center"
              width="200"
            >
              <template slot-scope="scope">
                {{
                  formatParamValue(scope.row.paramObjectList[0]) +
                  " " +
                  scope.row.paramObjectList[0].unit
                }}
              </template>
            </el-table-column>
            <el-table-column
              label="检测状态"
              prop="status"
              align="center"
              width="200"
            >
              <template slot-scope="scope">
                <div style="display: flex; justify-content: center">
                  <div
                    :class="scope.row.status == '正常' ? 'zc' : 'ejbj'"
                  ></div>
                  <div>
                    {{ scope.row.status }}
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { gmExport } from "@/api/emergency/perimeterData";
import { getPeriodData, getPeriodList } from "@/api/emergency/workData";

export default {
  name: "detail",
  props: ["facId", "paramId", "name", "max", "min"],
  data() {
    return {
      // facId: "", // 路由传参-新堆快堆
      // paramId: "", // 路由传参-参数记录id
      // name: "",
      // max: "",
      // min: "",
      //==============
      pickerOptions: {
        shortcuts: [
          {
            text: "最近4小时",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 4);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近12小时",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 12);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近1天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近7天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      queryParams: {
        dateRange: "",
      }, // 查询表单
      showAll: false,
      // 日期范围
      dateRange: [],
      detailData: [],
      detailData2: [],
      tableData: [],
      chartData: [],
      chartData2: [],
      // 其他信息
      dataAvg: "",
      dateMax: "", // 分之十克
      dataMax: "", // 平均值
      dataMin: "", // 最小值
      dataNumber: "", //
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      status: "",

      levelOne: "",
      levelTwo: "",
      myChart: null,
      temprow: null,
      conheight: 550,
    };
  },
  mounted() {
    // this.getChartsDataFlag();
    // 获取详情页的列表数据
    this.init();
    this.getAllList();
    // 获取某一GM管设备历史数据的其他信息
    // 页面高度显示自适应
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
  },
  methods: {
    init() {
      const end1 = new Date();
      const start1 = new Date();
      start1.setTime(start1.getTime() - 3600 * 1000 * 4);
      this.dateRange = [start1, end1];
    },
    getAllList() {
      // 时间范围大于一天，显示表格形式
      var begin = new Date(this.dateRange[0]).getTime();
      var end = new Date(this.dateRange[1]).getTime();
      var diff = Math.floor((end - begin) / 86400 / 1000);
      if (diff > 7) {
        this.showAll = true;
        // 获取分页的数据
        this.getDataList();
      } else {
        this.showAll = false;
        // 获取不分页数据
        this.getNoDataList();
      }
      // this.getOtherInfo();
    },
    // 获取不分页的数据
    getNoDataList() {
      // const params = {
      //   facId: this.facId,
      //   ids: this.paramId,
      //   beginTime: new Date(this.parseTime(this.dateRange[0])).getTime(),
      //   endTime: new Date(this.parseTime(this.dateRange[1])).getTime(),
      // };
      let str = "/static/emergency/workData/detail";
      let str1 =
        this.facId == 1
          ? str + this.paramId + ".json"
          : str + "s" + this.paramId + ".json";
      this.$axios.get(str1).then((res) => {
        // getPeriodData(params).then((res) => {
        console.log(res, "获取不分页数据");
        // let res = res.data;
        if (res.data.code == 200 && res.data.data != []) {
          this.detailData = res.data.data.reverse().slice(0, 20);
          this.ok = res.data.data;
          console.log(this.detailData, "===============");
          // 拼接图标数组-先置空再push
          let temp1 = [];
          let temp2 = [];
          res.data.data.forEach((item, index, array) => {
            temp1.push(item.collectTime);
            temp2.push(item.paramObjectList[0].paramNumber);
          });
          this.chartData = temp1;
          this.chartData2 = temp2;
          // console.log(this.chartData, this.chartData2, "====chartdata======");
          this.drawChart();
          let _this = this;
          setTimeout(() => {
            console.log("hjhskdhjahds", _this.detailData);
            _this.detailData = _this.ok;
          }, 100);
        } else {
          this.detailData = [];
          this.chartData = [];
          this.chartData2 = [];
          // console.log(this.chartData, this.chartData2, "====chartdata======");
          this.drawChart();
        }
      });
    },
    // 获取分页数据
    getDataList() {
      const params = {
        facId: this.facId,
        ids: this.paramId,
        // beginTime: this.parseTime(this.dateRange[0]),
        // endTime: this.parseTime(this.dateRange[1]),
        // beginTime: this.dateRange[0].getTime(),
        // endTime: this.dateRange[1].getTime(),
        beginTime: new Date(this.parseTime(this.dateRange[0])).getTime(),
        endTime: new Date(this.parseTime(this.dateRange[1])).getTime(),
        ...this.queryParams,
      };
      debugger;
      getPeriodList(params).then((res) => {
        if (res.code == 200) {
          this.detailData = res.rows.reverse();
          this.total = res.total;
          // 状态是正常还是异常
          // console.log(res.rows, "00000000000000000000000000000000");
          this.detailData.forEach((item, index, array) => {
            if (
              item.paramObjectList[0].paramNumber <=
                item.paramObjectList[0].max &&
              item.paramObjectList[0].paramNumber >= item.paramObjectList[0].min
            ) {
              item.status = "正常";
            } else {
              item.status = "异常";
            }
          });
        }
      });
    },
    drawChart() {
      // console.log("drawchart", this.chartData, this.chartData2);
      var that = this;
      var chartDom = document.getElementById("chart");
      var myChart = this.$echarts.init(chartDom);
      this.myChart = myChart;
      const max = parseInt(this.max);
      const min = parseInt(this.min);
      var option = {
        title: {
          text: "",
          left: "1%",
        },
        tooltip: {
          trigger: "axis",
        },
        // lineStyle: {
        //   color: "#1890ff",
        // },
        grid: {
          left: "5%",
          right: "15%",
          bottom: "10%",
        },
        xAxis: {
          // data: data.map(function (item) {
          //   return item[0];
          // }),
          data: that.chartData.reverse(),
        },
        yAxis: {},
        dataZoom: [
          {
            // startValue: "2014-06-01 00:00:00",
          },
          {
            type: "inside",
          },
        ],
        visualMap: {
          top: 50,
          right: 10,
          pieces: [
            {
              gt: 0,
              lte: min,
              color: "#096dd9",
            },
            {
              gt: min,
              lte: max,
              color: "#e19b16",
            },
            {
              gt: max,
              // lte: parseInt(levelTwo) + 30,
              color: "#e84b3f",
            },
          ],
          outOfRange: {
            color: "#e84b3f",
          },
        },
        series: {
          name: "当前值",
          type: "line",
          data: that.chartData2,
          markLine: {
            symbol: ["none", "none"], //去掉箭头
            itemStyle: {
              normal: {
                lineStyle: {
                  type: "solid",
                  color: {
                    // 设置渐变
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "red ", // 0% 处的颜色
                      },
                      {
                        offset: 1,
                        color: "#fff", // 100% 处的颜色
                      },
                    ],
                    // color: "#e84b3f",
                    global: false, // 缺省为 false
                  },
                },
                label: {
                  show: true,
                  position: "middle",
                },
              },
            },
            data: [
              {
                yAxis: this.min, //这里设置false是隐藏不了的，可以设置为-1
              },
              {
                yAxis: this.max, //这里设置false是隐藏不了的，可以设置为-1
              },
            ],
          },
        },
      };
      option && myChart.setOption(option);
      // 图形和表格联动
      //  移入该区域时，高亮
      var self = this;
      this.myChart.on("click", function (params) {
        // console.log(params, params.dataIndex); //此处写点击事件内容
        var tableDom = document.getElementById("tableBox");
        self.temprow = params.dataIndex;
        // console.log(self.temprow, " self.temprow");
      });
    },
    // 更新chart
    changeChart() {
      if (!this.showAll) {
        this.$nextTick(() => {
          this.drawChart();
        });
      }
    },

    // 查询
    search() {
      this.getAllList();
      this.getHeight();
    },
    reset() {
      const end1 = new Date();
      const start1 = new Date();
      start1.setTime(start1.getTime() - 3600 * 1000 * 4);
      this.dateRange = [start1, end1];
      this.getAllList();
      // chart重画
      this.chartData = [];
      this.chartData2 = [];
      this.drawChart();
    },
    handleClickChange(row, event, column) {
      // console.log(row.index, this.myChart, row, column, row.active);
      this.temprow = row.index;
      this.myChart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: row.index,
      });
    },
    tableRowClassName({ row, rowIndex }) {
      // console.log("tableRowClassName");
      //把每一行的索引放进row
      row.index = rowIndex;
      // if (row.active == true) {
      if (rowIndex == this.temprow) {
        return "light-row";
      }
    },
    goback() {
      this.$emit("changePage");
    },
    /*处理小数和科学计数法的函数*/
    formatParamValue(item) {
      if (this.praseStrEmpty(item.paramNumber) != "") {
        if (Number(item.scmFlag) == 1) {
          let str = "";
          let num = Math.abs(item.paramNumber);
          let p = num == 0 ? 0 : Math.floor(Math.log(num) / Math.LN10);
          let m = 0;
          if (num.toString().indexOf(".") > -1) {
            m = num.toString().split(".")[1].length;
          }

          let n =
            Number(num.toString().replace(".", "")) * Math.pow(10, -p - m);
          str =
            (item.paramNumber >= 0 ? "" : "-") +
            parseFloat(n).toFixed(item.bit) +
            "E" +
            (p >= 0 ? "+" : "-");
          let pNew = (new Array(2).join(0) + Math.abs(p)).slice(-2);
          str += pNew;
          return str;
        }
        if (Number(item.bit) >= 0) {
          let num = parseFloat(item.paramNumber).toFixed(item.bit);
          return num;
        }
      }
      return item.paramNumber;
    },
    getHeight() {
      this.conheight = window.innerHeight * 0.6;
      // console.log(this.conheight, "0000000");
    },
  },
};
</script>

<style scoped lang="scss">
.card-content1 {
  // height: 460px;
  // display: flex;
  .card-table {
    // width: 75%;
    width: 100%;
    // height: 400px;
  }
  .card-left {
    width: 25%;
    .left-detail {
      min-height: 270px;
      font-size: 14px;
      width: 260px;
      padding: 20px 0px 10px 10px;
      // background-color: rgb(116, 75, 75);
      border: 1px solid #cacaca;
    }
  }
}
// title
.title {
  height: 40px;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  font-weight: bold;
  padding: 4px 10px 20px 10px;
  .title-name {
    width: 80px;
  }
  .title-refresh {
    width: 70px;
    color: #1890ff;
    text-align: right;
    padding-right: 15px;
  }
}
.right-title {
  height: 40px;
  font-size: 14px;
  margin-left: 40px;
}

// el-form
::v-deep .el-form {
  height: 55px;
  padding: 10px;
  .el-form-item__label {
    font-size: 14px;
    font-weight: bold;
    color: black;
  }
}
// ::v-deep .el-input__inner {
//   width: 200px;
//   height: 28px;
//   font-size: 14px;
// }
// .el-button {
//   height: 28px;
//   width: 64px;
//   font-size: 14px;
//   line-height: 5px;
// }
.red {
  color: red;
}
.green {
  color: green;
}
.card-box {
  padding: 0px;
  // margin-bottom: 20px;
}
// right-left
.card-left {
  width: 35%;
  height: 600px;
  // background-color: rgb(124, 66, 66);
}
.card-right {
  // width: 800px;
  width: 60%;
  height: 580px;
  // padding-left: 40px;
  // background-color: rgb(159, 216, 127);
  .title-name {
    margin-left: 20px;
    width: 80px;
    font-size: 14px;
    font-weight: bold;
  }
  .data-analyse {
    margin: 10px;
    height: 100px;
    width: 300px;
    .analyse-title {
      height: 50px;
      padding: 10px 10px 0px 10px;
      font-weight: bold;
      font-size: 14px;
    }
    .analyse-itemlist {
      height: 60px;
      width: 600px;
      margin-left: 50px;
      font-size: 14px;
      display: flex;
      flex-wrap: wrap;
    }
    .analyse-item {
      min-width: 300px;
      height: 30px;
      margin: 0px;
      padding: 0px;
    }
  }
}
.card-title {
  padding-left: 10px;
  margin: 6px 0px;
  font-size: 16px;
  font-weight: bold;
}

// table
::v-deep .el-table {
  // height: 460px;
  border: 0;
  padding-left: 10px;
  .el-table__header tr,
  .el-table__header th {
    height: 36px;
    color: black;
    font-size: 14px;
  }
  .el-table__body tr,
  .el-table__body td {
    height: 36px !important;
  }
  // 修改行高
  .cell {
    line-height: 20px;
  }
  .light-row {
    background: #f5f7fa;
  }
}
// 检测状态
.zc {
  height: 7px;
  width: 7px;
  border-radius: 50%;
  background-color: green;
  margin: auto 9px;
}
.yjbj {
  height: 7px;
  width: 7px;
  border-radius: 50%;
  background-color: #e19b16;
  margin: auto 9px;
}
.ejbj {
  height: 7px;
  width: 7px;
  border-radius: 50%;
  background-color: #e84b3f;
  margin: auto 9px;
}
.lx {
  height: 7px;
  width: 7px;
  border-radius: 50%;
  background-color: gray;
  margin: auto 9px;
}
.zc-t {
  color: green;
}
.yjbj-t {
  color: #e19b16;
}
.ejbj-t {
  color: #e84b3f;
}
.lx-t {
  color: gray;
}
.flexDiv {
  display: flex;
  justify-content: space-between;
}
.min {
  color: green;
}
.max {
  color: red;
}
</style>
